#!/bin/bash

verbose=0

usage()
{
        echo "Usage: $0 [-v] [-h] -i infile -o outfile -m month"
}

process()
{
        if [ -e $1 ]; then
                echo "$1 exists"
                return 17
        fi

        dir=$(mktemp -d)
        if [ $? -ne 0 ]; then
                echo "mktemp error"
                return $?
        fi

        tar xf $2 -C $dir > /dev/null 2>&1
        if [ $? -ne 0 ]; then
                echo "tar error"
                return $?
        fi

        for info in $(find $dir -name "*.info"); do
                echo "process $(basename $info)"

                ip=${info%.*}

                ./lich.license_gen -i $info -o $ip.license > /dev/null 2>&1 << EOF
1@3\$5^7*qWeRtYuI
$month
EOF
                if [ $? -ne 0 ]; then
                        echo "error"
                        return $?
                fi

                rm -f $info
        done

        tar cf $1 $dir/* > /dev/null 2>&1
        if [ $? -ne 0 ]; then
                echo "tar error"
                return $?
        fi

        rm -rf $dir
}

while getopts vhi:o:m: option; do
        case $option in
                v)
                        verbose=1
                        break
                        ;;
                h)
                        usage
                        exit 0
                        ;;
                i)
                        infile="$OPTARG"
                        ;;
                o)
                        outfile="$OPTARG"
                        ;;
                m)
                        month="$OPTARG"
                        ;;
                ?)
                        usage
                        exit 1
                        ;;
        esac
done

if [ -z "$outfile" -o -z "$infile"  -o -z "$month" ]; then
        usage
        exit 2
fi

process $outfile $infile $month
exit $?
